<?php

class RamCache
{
	private static $instance = null;
	private $link = null;
	private $conf;
	private $prefix;

	private function __construct()
	{
		$this->conf = config_get('MEMCACHE');
		if ($this->conf['enabled'])
		{
			$this->link = new Memcache();
			$this->link->addServer($this->conf['server'], $this->conf['port']);
			$this->prefix = $this->conf['prefix'];
		}
	}

	public static function GetInstance()
	{
		if (is_null(self::$instance))
		{
			self::$instance = new RamCache;
		}
		
		return self::$instance;
	}

	function Set($key, $value, $expiration = 300)
	{
		$key = $this->prefix . $key;
		
		if (!is_null($this->link))
		{
			if (isset($_GET['debug'])) print "cache write: $key<br>\n";
			return $this->link->set($key, $value, $expiration);
		}
		else return null;
	}

	function Get($key)
	{
		$key = $this->prefix . $key;
		
		if (!is_null($this->link))
		{
			$ret = $this->link->get($key);
			if (isset($_GET['debug'])) print "cache ".($ret? 'hit' : 'miss').": $key<br>\n";
			return $ret;
		}
		else return null;
	}

	function Replace($key, $value, $expiration = 300)
	{
		$key = $this->prefix . $key;
		
		if (!is_null($this->link))
		{
			if (isset($_GET['debug'])) print "cache write: $key<br>\n";
			return $this->link->replace($key, $value, $expiration);
		}
		else return null;
	}

	function Delete($key)
	{
		$key = $this->prefix . $key;
		
		if (!is_null($this->link))
		{
			if (isset($_GET['debug'])) print "cache remove: $key<br>\n";
			return $this->link->delete($key);
		}
		else return null;
	}
}

?>